function cellDistributionAnalysis
% FUNCTION CELLDISTRIBUTIONANALYSIS calculates and displays relative
% locations of cells in a cell list.
% written by Taro Kiritani, tarokiritani2008@u.northwestern.edu 12/19/2010

hdist = figure;
set(hdist,'HandleVisibility','off')
celltype = 'sp2st';
[CellList,connectionBoolean] = makeCellList(celltype);
R = [];
Theta = [];
connectionBoolean = [];
% calculate the relative positions of cells.
for k = 1:size(CellList,1)   
    % find the radial and cell direction vectors.
    cd(['C:\Data\Taro\CELLS\TK',CellList{k,1}]);
    try % if radVector, TwoCellVector cannot be found, just skip the inineration.
        [radVector, TwoCellVector] = cellPositionVector(CellList{k,1},CellList{k,2},CellList{k,3});

        % find distance between cells r and angle theta.
        for kk = 1:size(CellList{k,3}, 1)
            [r, theta] = cellPosPolar(radVector, TwoCellVector{CellList{k,3}(kk, 1), ...
                CellList{k,3}(kk, 2)});

            % plot cell position.
            [x, y] = pol2cart(theta, r);
            set(0,'CurrentFigure', hdist)
            set(hdist, 'HandleVisibility', 'on')
            % red if connected and blue if not connected.
            if CellList{k, 4}(kk) == 0
                rb = 'b';
            else
                rb = 'r';
            end
            scatter(x, y, 'tag', ['cell num: ', CellList{k,1}, ', pre post: ',...
                num2str(CellList{k,3}(kk,:))], 'MarkerFaceColor', rb,...
                'MarkerEdgeColor', rb)
            hold on;
            set(hdist, 'HandleVisibility', 'off')

            R = [R;r];
            Theta = [Theta;theta];
        end

        if ~isempty(r)
            connectionBoolean = [connectionBoolean;CellList{k,4}];  
        end
    catch
        keyboard
    end
    close all
end

set(0,'CurrentFigure', hdist)
set(hdist, 'HandleVisibility', 'on')
daspect([1 1 1])
title(celltype)
saveas(hdist,['C:\Data\Taro\ANALYSIS\multi_rec_project\connectivity\',celltype,'Scatter.fig'])
set(hdist, 'HandleVisibility', 'off')
% Here, small angles indicate shallower direction in the cortex.
R = R';
Theta = Theta';
save(['C:\Data\Taro\ANALYSIS\multi_rec_project\connectivity\',celltype,'Scatter.mat'], 'R', 'Theta', 'connectionBoolean');

% %% plot distribution along x axis.
% [x, y] = pol2cart(Theta,R);
% xConCount = histc(y(find(connectionBoolean == 0)),[-inf -200 -100 0 100 200 inf]);
% xUnconCount = histc(y(find(connectionBoolean == 1)),[-inf -200 -100 0 100
% 200 inf]);
% 
% 
% % plot the distribution of cells.
% figure;
% % plot unconnected pair
% pp(Theta(find(connectionBoolean ==0 )),R(connectionBoolean ==0 ),'LineStyle','none','Marker','^',...
%     'MaxValue',50 * ceil(max(R)/50),'CentreValue',0,'AngleStep',45,'RingStep',100,...
%     'RingUnits','um')
% % then connected pair
% hold on
% pp(Theta(find(connectionBoolean ==1 )),R(connectionBoolean ==1 ),...
%     'LineStyle','none','Marker','^','LineColor','r')
% ymax = max(ylim);
% ylim([0 ymax])
% daspect([1 1 1])
% legend({'Unconnected','Connected'})
% editFigExport(gcf,['C:\Data\Taro\ANALYSIS\multi_rec_project\connectivity\',celltype,'RTheta.eps'],5)
% saveas(gcf,['C:\Data\Taro\ANALYSIS\multi_rec_project\connectivity\',celltype,'RTheta.fig'])
% 
% 
% % plot the cell density.
% numArea = 4;
% for m = 1:numArea
%         cT = intersect(find(Theta >= pi/numArea * (m-1) ), find(Theta < pi/numArea * (m) )) % find indices of connections based on angle.
%         D(m,:) = histc(R(cT),[0 50 100 inf])
%         
%         try
%             Dconnect(m,:) = histc(R(cT(find(connectionBoolean(cT)))),[0 100 200 300]);       
%         catch
%             Dconnect(m,:) = [0 0 0];
%         end
%         
%         try
%             Dunconnect(m,:) = histc(R(cT(find(connectionBoolean(cT)==0))),[0 100 200 300]);       
%         catch
%             Dunconnect(m,:) = [0 0 0];
%         end
%         
%         Drate = Dconnect ./ (Dconnect + Dunconnect); % To do: check divided by 0 error.
% end
% 
% figure;
% bullseye(D(:,1:size(D,2)-1),'n',100,'rho',[0 5])%,'tht',[-90 90])
% figure;
% 
% % show the relationship between position and connectivity.
% bullseye(Drate(:,1:3),'n',100,'rho',[0 2])%'tht',[-90 90])
% colorbar
% title('CSt>CSp connection probability')
% % caxis([ ]) % if the colar scale has to be changed..
% 
% % label x axis
% xmax = xlim;
% text(xmax(1),-0.5,'\leftarrow \newlineWhite matter')
% text(xmax(2),-0.5,'\rightarrow \newlinePia')
% xlvector = [-300 -200 -100 0 100 200 300]; % these nums are shown along x asis.
% for xx = 1:length(xlvector)
%     text(xmax(1) + xmax(2)/(length(xlvector)-1) * 2 * (xx-1),-0.2,...
%         num2str(xlvector(xx)),'HorizontalAlignment','Center')
% end
% text(0,-0.5,'Distance (\mum)','HorizontalAlignment','Center')
% 
% % put texts in bullseye graph.
% for i = 1:size(D,1) % change theta.
%     for j = 1:size(D,2)-1 
%         theta = pi/8 * (2 * (i - 1) + 1);
%         r = xmax(2)/6 * (2 * (j - 1) + 1);
%         [posx,posy] = pol2cart(theta,r);
%         text(posx,posy,['$\frac{',num2str(Dconnect(i,j)),'}{',...
%             num2str(Dconnect(i,j)+Dunconnect(i,j)),'}$'],...
%             'interpreter','latex','BackgroundColor','w','HorizontalAlignment',...
%         'Center','VerticalAlignment','middle')
%     end
% end
% editFigExport(gcf,['C:\Data\Taro\ANALYSIS\multi_rec_project\connectivity\',celltype,'SpatialConnect.eps'],5)
% saveas(gcf,['C:\Data\Taro\ANALYSIS\multi_rec_project\connectivity\',celltype,'SpatialConnect.fig'])

end

function [CellList, connectionBoolean] = makeCellList(type)
% FUNCTION[CELLLIST, CONNECTIONBOOLEAN] = MAKECELLLIST load a excel cell
% list and returns the list of cells, CELLLIST and their connection
% CONNECTIONBOOLEAN.
% written by Taro Kiritani, tarokiritani2008@u.northwestern.edu 12/14/2010

if strcmp(type, 'sp2sp')
    cellxls = xlsread('C:\Data\Taro\CELLS\experimentsummary.xlsx','cellpairs','A5:F359');
elseif strcmp(type, 'st2sp')
    cellxls = xlsread('C:\Data\Taro\CELLS\experimentsummary.xlsx','cellpairs','A491:F605');%548
elseif strcmp(type, 'st2st')
    cellxls = xlsread('C:\Data\Taro\CELLS\experimentsummary.xlsx','cellpairs','A613:F756');
elseif strcmp(type, 'sp2st')
    cellxls = xlsread('C:\Data\Taro\CELLS\experimentsummary.xlsx','cellpairs','A371:F479');
end

for n = 1:size(cellxls,1)
    CellList{n,1} = cellxls(n,1);   % cell number
    CellList{n,2} = 'x4forCellDistAnalysis.tif';    % image file
    CellList{n,3} = cellxls(n,3);   % pre and post synaptic cell
    CellList{n,4} = cellxls(n,5);
end
connectionBoolean = cellxls(:,5);   % 1 if connected and 0 otherwise.

% exclude cells counted multiple times.
CellNumList = unique(cell2mat(CellList(:,1)));
for numCell = 1:size(CellNumList,1)
    sameCellList = find(cell2mat(CellList(:,1)) == CellNumList(numCell));
    CellList{sameCellList(1),3} = cat(1,CellList{sameCellList,3});
    CellList{sameCellList(1),4} = cat(1,CellList{sameCellList,4});
    try
    CellList(sameCellList(2:length(sameCellList)),:) = [];
    end
end

% change the format a bit so that cellDistributionAnalysis can read the
% cell list.
for k = 1:size(CellList,1)
    CellList{k,1} = ['0',num2str(CellList{k,1})]; % cell # is a four digit number.
    CellList{k,3} = floor([CellList{k,3}/10, mod(CellList{k,3},10)]);
end

% no image data.

% CellList(7,:)=[];

end